#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______    _______   _______ #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \  |       \ |   ____| #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  | |  .--.  ||  |__     #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  | |  |  |  ||   __|     #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  | |  '--'  ||  |____     #
#|__|     | _| `._____||_______||_______| \______| \______/  |_______/ |_______|   #
#                                                                                 #
#                             Small Games Module                                 #
#                             Modular FrameWork                                 #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
import random
	
# Random dice roller
def dice(globalvars, msgvars):

	# Checks game module is on
	if msgvars["features"][5]:
	
		die = random.choice([1,2,3,4,5,6])
		if die == 6:
			msgvars["server"].privmsg(msgvars["destination"], '%s: You rolled a... %s You ROCK!' % (msgvars["source"], die))
		else:
			msgvars["server"].privmsg(msgvars["destination"], '%s: You rolled a... %s You FAIL!' % (msgvars["source"], die))
	else:
		msgvars["server"].privmsg(destination, "Sorry but that feature is disabled here.")
		
# Rock paper scissors game
def rps(globalvars, msgvars):

	# Checks game module is on
	if msgvars["features"][5]:
	
		# Checks for input length
		if len(msgvars["command"]) > 1:

			# Checks if message is gameplay
			if msgvars["command"][1].lower() in ['paper', 'rock', 'scissors', 'r', 'p', 's']:
				# Randomly chooses and checks human choice
				computer = random.choice(['rock', 'paper', 'scissors'])
				if msgvars["command"][1].lower() == 'rock' or msgvars["command"][1].lower() == 'r':
					human = 'rock'
				elif msgvars["command"][1].lower() == 'paper' or msgvars["command"][1].lower() == 'p':
					human = 'paper'
				elif msgvars["command"][1].lower() == 'scissors' or msgvars["command"][1].lower() == 's':
					human = 'scissors'
				else:
					msgvars["server"].privmsg(msgvars["destination"], "You must choose rock, paper, or scissors.")
					human = ''
			
				# Calculates win/lose/draw
				if computer == human:
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. It's a draw." % (msgvars["source"], computer))
					win = "draw"
				elif computer == 'rock' and human == 'paper':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Win!" % (msgvars["source"], computer))
					win = "win"
				elif computer == 'rock' and human == 'scissors':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Lose!" % (msgvars["source"], computer))
					win = "lose"
				elif computer == 'paper' and human == 'rock':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Lose!" % (msgvars["source"], computer))
					win = "lose"
				elif computer == 'paper' and human == 'scissors':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Win!" % (msgvars["source"], computer))
					win = "win"
				elif computer == 'scissors'and human == 'rock':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Win!" % (msgvars["source"], computer))
					win = "win"
				elif computer == 'scissors' and human == 'paper':
					msgvars["server"].privmsg(msgvars["destination"], "%s: I chose %s. You Lose!" % (msgvars["source"], computer))
					win = "lose"
		
				# Reads the database
				globalvars["cursor"].execute("select wins from rps where chanid = %s and nick = %s", (msgvars["chanid"], msgvars["source"]))
				data = globalvars["cursor"].fetchall()
				if len(data) > 0:
					for row in data:
						if win == "lose":
							wins = row[0] - 1
							if wins < 0:
								wins = 0
						elif win == "win":
							wins = row[0] + 1
						else:
							wins = row[0]
						globalvars["cursor"].execute("update rps set wins = %s where nick = %s and chanid = %s", (wins, msgvars["source"], msgvars["chanid"]))
				else:
					globalvars["cursor"].execute("insert into rps (chanid, nick, wins) values (%s, %s, 1)", (msgvars["chanid"], msgvars["source"]))
	
			# Checks if message is a score request
			elif msgvars["command"][1].lower() == 'score':
		
				# Outputs to 5
				globalars["cursor"].execute("select nick, wins from rps where chanid = %s order by wins desc limit 5", (msgvars["chanid"]))
				data = globalvars["cursor"].fetchall()
				places = ('First', 'Second', 'Third', 'Fourth', 'Fifth')
				index = 0
				for row in data:
					msgvars["server"].privmsg(msgvars["destination"], "%s is %s with %s wins!" % (places[index], row[0], str(row[1])))
					index = index + 1

				# Outputs your score
				globalvars["cursor"].execute("select wins from rps where chanid = %s and nick = %s", (msgvars["chanid"], msgvars["source"]))
				row = globalvars["cursor"].fetchone()
				msgvars["server"].privmsg(msgvars["destination"], "%s: Your score is %s wins!" % (msgvars["source"], str(row[0])))
		
		# Replies  not enough data
		else:
			msgvars["server"].privmsg(msgvars["destination"], "I need a bit more info.")
	else:
		msgvars["server"].privmsg(destination, "Sorry but that feature is disabled here.")
			
def autoload(globalvars):
	
	# Loads oncall
	oncall = {'dice':dice, 'rps':rps}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
	
def load(globalvars, msgvars):
	
	# Loads oncall
	oncall = {'dice':dice, 'rps':rps}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a function named %s." % (feature[0]))
	return True
			
def unload(globalvars, msgvars, reloadmodule = False):
	
	# Unloads oncall
	oncall = {'dice':dice, 'rps':rps}
	for feature in oncall.items():
		if feature[0] in globalvars["oncall"].keys():
			del globalvars["oncall"][feature[0]]
	return True
